$(function() {// jQuery on DOM ready shortcut
	
	var lexicon = {};
	var controlURL = '/assets/modules/mxw/control/mxw.controller.php';
	var scrollPos = 0;
	
	/**
	 * Initialization function.
	 * This function gets the lexicon for the current
	 * manager language into a local variable then
	 * calls "loadView()" to get the products overview
	 */
	var init = function(){
		// Add any other initiation items here:
		$.post(controlURL,
			{action: 'lexicon'},
			function( data ) {
				lexicon = data;
				loadView({action: 'overview', direction: 'left'});
			},
			'json'
		);
	}
	
	/**
	 * loadingMessage
	 * 
	 * Returns a formatted loading message for processor
	 * intensive view rendering.
	 */
	var loadingMessage = function() {
		var loading = '<h1 id="blockMessage">'+
			'<img src="/assets/modules/mxw/view/appearance/images/arrows.gif">'+
			lexicon.blockui+
			'...</h1>';
		return loading;
	} // [END loadingMessage]
	
	/**
	 * loadView
	 * 
	 * This function loads a toolbar and the document content
	 * for a given action.
	 */
	var loadView = function( params ) {
		
		if (params.action == 'overview') {
			$.blockUI({ message: loadingMessage() });
		}
		
		$.post(controlURL,
			params,
			function(data) {
				$('#toolbar').html(data.toolbar);
				$('.toolbar-items').show('drop', { direction: 'up' }, 400);
				$('.toolbar-items li a').tooltip({ positionLeft: true, showURL: false, track: true, delay: 200, fade: 200 });
				$('#view').html(data.content).animate({opacity: 1}, 0,function(){
					$('#productsTable').dataTable({
						'oLanguage': {
									'sLengthMenu': lexicon.mxw_table_length,
									'sZeroRecords': lexicon.mxw_table_empty,
									'sInfo': lexicon.mxw_table_info,
									'sInfoEmtpy': lexicon.mxw_table_empty_info,
									'sInfoFiltered': lexicon.mxw_table_filtered
								}
					})
					.css('width', '100%');
					
					$('#productsTable tr.product').hover(
						function() {
							$('#productsTable tr.product td').addClass('sectionHeader');
						},
						function() {
							$('#productsTable tr.product td').removeClass('sectionHeader');
						}
					);
					
					$('#view').show('drop', { direction: params.dropIn }, 400, function(){
						$('body').css('overflow-x', 'visible');
					});
					$('#productsTable abbr').tooltip({ positionLeft: true, showURL: false, track: true, delay: 200, fade: 200 });
					$('.productInput abbr').tooltip({ showURL: false, track: true, delay: 200, fade: 200 });
					if (params.callback) params.callback();
					$('form').listenForChange();
					$('form input').change(function(){
						edit.dirty = true;
						edit.update();
					});
					
					$.unblockUI();
				});
			},
			'json'
		);
	} // [END loadView]
	
	/**
	 * modalShow
	 * 
	 * This convenience function displays a jQuery modal
	 * dialog with the title and message parameters.
	 */
	var modalShow = function( info ) {
		if (!info.buttons) {
			info.buttons = {};
			info.buttons[lexicon.cancel] = function() {
				$(this).dialog('close');
			}

			info.buttons[lexicon.ok] = function() {
				$(this).dialog('close');
			}
		}
		
	    $('<div id="mxwMessage">'+info.message+'</div>')
	        .appendTo('#MXW')
	        .dialog({
	            bgiframe: true,
	            modal: true,
	            draggable: true,
				position: ['center', 50],
				resizable: false,
				closeOnEscape: false,
	            hide: 'drop',
	            show: 'drop',
				open: function(event, ui) { 
					$('body').css('overflow-x', 'hidden');
					if (info.state) {
						$('.ui-dialog-titlebar').addClass(info.state);
					}
				},
				focus: function(event, ui) {
					
				},
				close: function(event, ui) { 
					$('body').css('overflow-x', 'visible'); 
				},
	            title: info.title,
	            buttons: info.buttons
	        })
    } // [END modalShow]
	
	var edit = {
		dirty: false,
		update: function() {
			$('#save').removeClass('disabled');
			$('#save_close').removeClass('disabled');
		},
		clean: function() {
			$('#save').addClass('disabled');
			$('#save_close').addClass('disabled');
			edit.dirty = false;
		}
	};
	
	var processProductForm = function() {
		$('#product').submit(function() {
			if (edit.dirty) {
				determineToolbarAction('save');
				edit.clean();
				alert('Saved');
			}
			return false;
		});
	}
	
	/**
	 * Live binding of click event to toolbar items.
	 */
	$('.toolbar-items li a').live('click', function(){
		determineToolbarAction(this.rel);
	})
	
	var determineToolbarAction = function( whereTo ) {
		var params = {};
		params.action = whereTo;
		params.callback = null;
		params.dropIn = 'right';
		params.dropOut = 'left';
		
		var modals = {};
		var TBI = '<p><strong>TO BE IMPLEMENTED...</strong></p>';
		scrollPos = document.body.scrollTop;
		
		switch (params.action) {
		    case 'new_product':
		        params.callback = processProductForm;
		        break;

		    case 'orders':
				modals.state = 'ui-state-highlight';
				modals.title = '<span class="ui-icon ui-icon-info"></span>'+ lexicon.mxw_orders;
				modals.message = TBI + '<p>'+ lexicon.mxw_options_title +'</p>';
		        modalShow( modals );
				return false;
		        break;
		
		    case 'settings':
				modals.title = lexicon.edit_settings;
				modals.message = TBI + '<p>'+ lexicon.edit_settings +'</p>';
		        modalShow( modals );
				return false;
		        break;
		
		    case 'catalogs':
				modals.title = lexicon.mxw_tags;
				modals.message = TBI + '<p>'+ lexicon.mxw_tags_title +'</p>';
		        modalShow( modals );
				return false;
		        break;
		
		    case 'options':
				modals.title = lexicon.mxw_options;
				modals.message = TBI + '<p>'+ lexicon.mxw_options_title +'</p>';
		        modalShow( modals );
				return false;
		        break;
		
			case 'save':
				if (!edit.dirty) {
					return false;
				}
				params.action = 'overview';
				params.dropIn = 'left';
				params.dropOut = 'right';
				edit.clean();
				return false;
				break;
			
			case 'save_close':
				if (!edit.dirty) {
					return false;
				}
				params.action = 'overview';
				params.dropIn = 'left';
				params.dropOut = 'right';
				edit.dirty = false;
				break;
			
		    case 'cancel':
		        if (edit.dirty) {
					modals.state = 'ui-state-error';
					modals.title = '<span class="ui-icon ui-icon-alert"></span>'+lexicon.mxw_warning;
					modals.message = '<p>'+lexicon.mxw_has_changed+'</p>';
					modals.buttons = {};
					modals.buttons[lexicon.mxw_discard] = function() {
						
						params.action = 'overview';
						params.dropIn = 'left';
						params.dropOut = 'right';
						edit.dirty = false;
						$(this).dialog('close');
						$('body').animate({opacity: 1}, 500, function(){
							loadFromToolbar(params);							
						})
						return false;
					};
					modals.buttons[lexicon.mxw_continue_edit] = function() {
						document.body.scrollTop = scrollPos;
						$(this).dialog('close');
					};
					modalShow( modals );
					return false;
				}
				params.action = 'overview';
				params.dropIn = 'left';
				params.dropOut = 'right';
		        break;
		
			case 'overview':
		        params.dropIn = 'left';
				params.dropOut = 'right';
		        break;

		    default:
		        // CODE...
		        break;
		}
		
		loadFromToolbar( params );

		return false;
	}
	
	var loadFromToolbar = function( params ) {
		$('body').css('overflow-x', 'hidden');
		$('.toolbar-items').hide('drop', { direction: params.dropOut }, 500);
		$('#view').hide('drop', { direction: params.dropOut }, 500, function(){
			loadView(params);
		});
	}
	
	/**
	 * Live binding of click event to table rows.
	 */
	$('table#productsTable tr.product').live('click', function(){
		var params = {};
		params.action = 'edit_product';
		params.product_id = $(this).attr('rel');
		params.dropIn = 'right';
		params.dropOut = 'left';
		params.callback = processProductForm;
		$('body').css('overflow-x', 'hidden');
		$('.toolbar-items').hide('drop', { direction: params.dropOut }, 500);
		$('#view').hide('drop', { direction: params.dropOut }, 500, function(){
			loadView(params);
		});
	});
	
	// blockUI plugin default overrides.
	$.blockUI.defaults.css = {
		padding:        10, 
        margin:         0, 
        width:          '30%', 
        top:            '25%', 
        left:           '35%', 
        textAlign:      'center', 
        color:          '#333', 
        border:         '3px solid #999', 
        backgroundColor:'#eee', 
        cursor:         'wait'
	}
	$.blockUI.defaults.overlayCSS = {
		backgroundColor: '#eee', 
		opacity:         0.7
	}
	
	/**
	 * Call the init function when the DOM is ready
	 */
	init();
	
})